package com.mimo.gateway.filter;

import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;

import com.mimo.common.result.BaseResult;
import com.mimo.common.utils.JsonUtils;

public abstract class AbstractGlobalFilter implements GlobalFilter, Ordered {

  // 定义一个业务上排序基点,相关业务子类, 需要基于该权重
  protected static final int BIZ_FILTER_BASIC_ORDER = -100;

  /**
   * 从HTTP请求头获取对应的Key-Value
   *
   * @param param
   * @return
   */
  protected String getHttpHeader(ServerHttpRequest request, String param) {
    return request.getHeaders().getFirst(param);
  }

  protected String getHttpHeader(ServerWebExchange exchange, String param) {
    return getHttpHeader(exchange.getRequest(), param);
  }

  @Override
  public int getOrder() {
    return BIZ_FILTER_BASIC_ORDER;
  }

  /**
   * 封装返回值
   *
   * @param response
   * @param result
   * @return
   */
  protected DataBuffer getBodyBuffer(ServerHttpResponse response, BaseResult result) {
    return response.bufferFactory().wrap(JsonUtils.toJsonBytes(result));
  }

}
